//
//  BookModel.swift
//  SwiftUIBook
//
//  Created by True on 2023/8/3.
//

import Foundation

enum SaveKey: String {
    case FAVORITE_SITES_KEY = "FAVORITE_SITES"
    case FAVORITE_BOOKS_KEY = "FAVORITE_SBOOKS"
    case LAST_VIEW_URL = "LAST_VIEW_URL"
}


struct BookAPPData {
    
    init() {
        restoreStiesFromUserDefaults()
        if sites.count == 0 {
            sites = [
                FavoriteSite(id: 1.0, name: "飞速中文", urlString: "https://www.feisxs.com"),
                FavoriteSite(id: 2.0, name: "友友小说", urlString: "https://youyouxs.com")
            ]
            storeStiesInUserDefaults()
        }
        
        restoreBooksFromUserDefaults()
    }
    
    //MARK: - 小说网站收藏
    private(set) var sites: [FavoriteSite] = [FavoriteSite]()
    
    struct FavoriteSite: Codable, Identifiable {
        var id: Double
        let name: String
        let urlString: String
    }
    
    private func storeStiesInUserDefaults() {
        // 结构体需要转换成属性列表才能存储进UserDefault, 例如 字符串
        UserDefaults.standard.set(try? JSONEncoder().encode(sites), forKey: SaveKey.FAVORITE_SITES_KEY.rawValue)
    }
    
    mutating private func restoreStiesFromUserDefaults() {
        // 结构体需要转换成属性列表才能存储进UserDefault, 例如 字符串
        if let jsonData = UserDefaults.standard.data(forKey: SaveKey.FAVORITE_SITES_KEY.rawValue),
           let decodeData = try? JSONDecoder().decode([FavoriteSite].self, from: jsonData) {
            sites = decodeData
        }
    }
    
    mutating func addSite(_ site: FavoriteSite) {
        sites.append(site)
        storeStiesInUserDefaults()
    }
    
    mutating func deleteSite(at index: Int) {
        sites.remove(at: index)
        storeStiesInUserDefaults()
    }
    
    mutating func deleteSite(_ site: FavoriteSite) {
        sites.remove(site)
        storeStiesInUserDefaults()
    }
    
    //MARK: - 书籍收藏
    struct Book: Codable, Identifiable, Hashable {
        var id: Double
        let name: String
        let homePage: String // 目录页网址
    }
    private(set) var books = [Book]()
    
    private func storeBooksInUserDefaults() {
        UserDefaults.standard.set(try? JSONEncoder().encode(books), forKey: SaveKey.FAVORITE_BOOKS_KEY.rawValue)
    }
    
    mutating private func restoreBooksFromUserDefaults() {
        if let jsonData = UserDefaults.standard.data(forKey: SaveKey.FAVORITE_BOOKS_KEY.rawValue),
           let decodeData = try? JSONDecoder().decode([Book].self, from: jsonData) {
            books = decodeData
        }
    }
    
    mutating func addBook(_ book: Book) {
        books.append(book)
        storeBooksInUserDefaults()
    }
    
    mutating func deleteBook(_ book: Book) {
        books.remove(book)
        storeBooksInUserDefaults()
    }
    
    mutating func deleteBook(at indexSet: IndexSet) {
        books.remove(atOffsets: indexSet)
        storeBooksInUserDefaults()
    }
    
    //MARK: - 阅读章节信息
    struct Chapter {
        let title: String
        var text: String
    }
    private(set) var chapters = [Chapter]()
    
    mutating func newChapterInfo(_ chapter: Chapter) {
        if var oldIndex = chapters.firstIndex(where: { c in
            c.title == chapter.title
        }) {
            var chapter = chapter
            chapter.text = chapters[oldIndex].text + chapter.text
            chapters[oldIndex] = chapter
        } else {
            chapters.append(chapter)
        }
    }
    
    mutating func chapterClean() {
        chapters = [Chapter]()
    }
    
    var readText: String {
        var temp = ""
        
        // 拼接章节数据
        chapters.forEach { c in
            temp += c.title
            temp += "\n\n"
            temp += c.text
            temp += "\n\n============================\n"
        }
        
        return temp
    }
    
}


